package com.draemon.haixiawenti.mvc;


import com.draemon.haixiawenti.constant.CharConstant;
import com.draemon.haixiawenti.exception.NoResponseException;
import com.draemon.haixiawenti.exception.NoResponseVO;
import com.draemon.haixiawenti.util.HTTPUtil;
import com.draemon.haixiawenti.util.JSONUtil;
import com.draemon.haixiawenti.util.JvmUtil;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@ControllerAdvice
public class GlobalExceptionHandler {

    public static final String DEFAULT_ERROR_VIEW = "error";

    @ExceptionHandler(value = Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest req, HttpServletResponse response, Exception e) throws Exception {
        if(e != null && (e instanceof NoResponseException || e.getCause() instanceof NoResponseException)){
            if(HTTPUtil.isMobile(req) || HTTPUtil.isAjax(req)){
                printResult(response, new NoResponseVO());
                return new ModelAndView();
            }
        }
        ModelAndView mav = new ModelAndView();
        mav.addObject("url", req.getRequestURL() + "  " + req.getMethod());
        mav.addObject("headers", HTTPUtil.showHeaderString(req, CharConstant.HTML_NEW_LINE_CHAR));
        mav.addObject("cookies", HTTPUtil.showCookieString(req, CharConstant.HTML_NEW_LINE_CHAR));
        mav.addObject("params", HTTPUtil.showParamsString(req, CharConstant.HTML_NEW_LINE_CHAR));
        mav.addObject("message", e.getMessage());
        mav.addObject("exception", JvmUtil.printHTMLStackTrace(e, CharConstant.HTML_NEW_LINE_CHAR));
        mav.setViewName(DEFAULT_ERROR_VIEW);
        return mav;
    }

    private void printResult(HttpServletResponse response, Object obj){
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
            writer.write(JSONUtil.toJson(obj));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            if(writer != null){
                writer.close();
            }
        }
    }

}
